using System;
using System.Collections.Generic;
using System.Linq;
using System.Threading.Tasks;
using Acme.BookStore.FormWhx.Storehouse;
using Microsoft.EntityFrameworkCore;
using Volo.Abp.Application.Dtos;
using Volo.Abp.Domain.Repositories;

namespace Acme.BookStore.FormWhxDto.StorehouseDto
{
    public class WarehouseOperationLogAppService : BookStoreAppService, IWarehouseOperationLogAppService
    {
        private readonly IRepository<WarehouseOperationLog, Guid> _operationLogRepository;

        public WarehouseOperationLogAppService(
            IRepository<WarehouseOperationLog, Guid> operationLogRepository)
        {
            _operationLogRepository = operationLogRepository;
        }

        public async Task<PagedResultDto<WarehouseOperationLogDto>> GetListAsync(WarehouseOperationLogQueryDto input)
        {
            var query = await _operationLogRepository.GetQueryableAsync();

            // 应用筛选条件
            if (!string.IsNullOrWhiteSpace(input.OperationType))
            {
                query = query.Where(x => x.OperationType == input.OperationType);
            }

            if (!string.IsNullOrWhiteSpace(input.Operator))
            {
                query = query.Where(x => x.Operator.Contains(input.Operator));
            }

            if (input.OperationTimeStart.HasValue)
            {
                query = query.Where(x => x.OperationTime >= input.OperationTimeStart.Value);
            }

            if (input.OperationTimeEnd.HasValue)
            {
                query = query.Where(x => x.OperationTime <= input.OperationTimeEnd.Value);
            }

            // 新增：按仓库ID过滤
            if (input.WarehouseId.HasValue)
            {
                query = query.Where(x => x.WarehouseId == input.WarehouseId.Value);
            }

            // 获取总数
            var totalCount = await query.CountAsync();

            // 排序和分页
            query = query.OrderByDescending(x => x.OperationTime)
                        .Skip(input.SkipCount)
                        .Take(input.MaxResultCount);

            // 执行查询
            var items = await AsyncExecuter.ToListAsync(query);

            // 转换为DTO
            var dtos = items.Select(item => new WarehouseOperationLogDto
            {
                Id = item.Id,
                OperationType = item.OperationType,
                Operator = item.Operator,
                OperationTime = item.OperationTime,
                Description = item.Description,
                WarehouseId = item.WarehouseId,
                WarehouseCode = item.WarehouseCode,
                WarehouseName = item.WarehouseName,
                CreationTime = item.CreationTime,
                CreatorId = item.CreatorId,
                LastModificationTime = item.LastModificationTime,
                LastModifierId = item.LastModifierId
            }).ToList();

            return new PagedResultDto<WarehouseOperationLogDto>(totalCount, dtos);
        }
    }
} 